package com.lanou.moving.view;

import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AlertDialog;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.style.StyleSpan;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.lanou.moving.R;
import com.lanou.moving.net.DownloadProgressListener;
import com.lanou.moving.net.FileDownloader;
import com.lanou.moving.utils.MyConfig;

import java.io.File;
import java.text.NumberFormat;

/**
 * Created by 梁树珍 on 15/10/30.
 */
public class CommonProgressDialog extends AlertDialog {


    private ProgressBar mProgress;
    private TextView mProgressNumber;
    private TextView mProgressPercent;
    private TextView download_song, download_singer;

    private Handler mViewUpdateHandler;
    private int mMax;
    private CharSequence mMessage;
    private boolean mHasStarted;
    private int mProgressVal;

    private String TAG = "CommonProgressDialog";
    private String mProgressNumberFormat;
    private NumberFormat mProgressPercentFormat;

    public CommonProgressDialog(Context context) {
        super(context);
        // TODO Auto-generated constructor stub
        initFormats();
    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.common_progress_dialog);
        mProgress = (ProgressBar) findViewById(R.id.progress);
        mProgressNumber = (TextView) findViewById(R.id.progress_number);
        mProgressPercent = (TextView) findViewById(R.id.progress_percent);
        download_song = (TextView) findViewById(R.id.download_song);
        download_singer = (TextView) findViewById(R.id.download_singer);

        mViewUpdateHandler = new Handler() {


            @Override
            public void handleMessage(Message msg) {
                // TODO Auto-generated method stub
                if (msg.what == 1) {
                    mProgress.setProgress(msg.getData().getInt("size"));
                    int progress = mProgress.getProgress();
                    int max = mProgress.getMax();
                    double dProgress = (double) progress / (double) (1024 * 1024);
                    double dMax = (double) max / (double) (1024 * 1024);
                    if (mProgressNumberFormat != null) {
                        String format = mProgressNumberFormat;
                        mProgressNumber.setText(String.format(format, dProgress, dMax));
                    } else {
                        mProgressNumber.setText("");
                    }
                    if (mProgressPercentFormat != null) {
                        double percent = (double) progress / (double) max;
                        SpannableString tmp = new SpannableString(mProgressPercentFormat.format(percent));
                        tmp.setSpan(new StyleSpan(android.graphics.Typeface.BOLD),
                                0, tmp.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                        mProgressPercent.setText(tmp);
                    } else {
                        mProgressPercent.setText("");
                    }

                }
            }
        };
        onProgressChanged();
        if (mMessage != null) {
            setMessage(mMessage);
        }
        if (mMax > 0) {
            setMax(mMax);
        }
        if (mProgressVal > 0) {
            setProgress(mProgressVal);
        }
    }

    private void initFormats() {
        mProgressNumberFormat = "%1.2fM/%2.2fM";
        mProgressPercentFormat = NumberFormat.getPercentInstance();
        mProgressPercentFormat.setMaximumFractionDigits(0);
    }

    private void onProgressChanged() {
        mViewUpdateHandler.sendEmptyMessage(0);


    }

    public void setProgressStyle(int style) {
        //mProgressStyle = style;
    }

    public int getMax() {
        if (mProgress != null) {
            return mProgress.getMax();
        }
        return mMax;
    }

    public void setMax(int max) {
        if (mProgress != null) {
            mProgress.setMax(max);
            onProgressChanged();
        } else {
            mMax = max;
        }
    }

    public void setIndeterminate(boolean indeterminate) {
        if (mProgress != null) {
            mProgress.setIndeterminate(indeterminate);
        }
//		else {
//			mIndeterminate = indeterminate;
//		}
    }

    public void setProgress(int value) {
        if (mHasStarted) {
            mProgress.setProgress(value);
            onProgressChanged();
        } else {
            mProgressVal = value;
        }
    }

    public void setName(String song, String singer) {
        download_song.setText(song);
        download_singer.setText(singer);
        MyConfig.putSharePre(getContext(), "songName", "songName", song);
        MyConfig.putSharePre(getContext(), "singerName", "singerName", singer);
    }

    public int getProgress() {
        return mProgress.getProgress();
    }


    @Override
    protected void onStart() {
        // TODO Auto-generated method stub
        super.onStart();
        mHasStarted = true;
    }


    @Override
    protected void onStop() {
        // TODO Auto-generated method stub
        super.onStop();
        mHasStarted = false;
    }

    /*
             * 由于用户的输入事件(点击button, 触摸屏幕....)是由主线程负责处理的，如果主线程处于工作状态，
             * 此时用户产生的输入事件如果没能在5秒内得到处理，系统就会报“应用无响应”错误。
             * 所以在主线程里不能执行一件比较耗时的工作，否则会因主线程阻塞而无法处理用户的输入事件，
             * 导致“应用无响应”错误的出现。耗时的工作应该在子线程里执行。
             */
    private DownloadTask task;


    //退出方法
    private void exit() {
        if (task != null)
            task.exit();
    }


    /**
     * 下载方法
     */
    public void download(String path, File savDir) {
        task = new DownloadTask(path, savDir);
        new Thread(task).start();
    }

    /**
     * UI控件画面的重绘(更新)是由主线程负责处理的，如果在子线程中更新UI控件的值，更新后的值不会重绘到屏幕上
     * 一定要在主线程里更新UI控件的值，这样才能在屏幕上显示出来，不能在子线程中更新UI控件的值
     * <p>
     * <p>
     * <p>
     * 下载任务的线程 内部类
     */
    private final class DownloadTask implements Runnable {
        private String path;
        private File saveDir;
        private FileDownloader loader;


        //构造方法
        public DownloadTask(String path, File saveDir) {
            this.path = path;
            this.saveDir = saveDir;
        }

        /**
         * 退出下载
         */
        public void exit() {
            if (loader != null)
                loader.exit();
        }


        //下载进度条
        DownloadProgressListener downloadProgressListener = new DownloadProgressListener() {
            @Override
            public void onDownloadSize(int size) {
                Message msg = new Message();
                msg.what = 1;
                msg.getData().putInt("size", size);
                mViewUpdateHandler.sendMessage(msg);
            }
        };


        //线程执行方法
        //进度条
        public void run() {
            try {
                // 实例化一个文件下载器
                loader = new FileDownloader(getContext(), path,
                        saveDir, 3);
                // 设置进度条最大值
                mProgress.setMax(loader.getFileSize());
                loader.download(downloadProgressListener);
            } catch (Exception e) {
                e.printStackTrace();
                mViewUpdateHandler.sendMessage(mViewUpdateHandler.obtainMessage(-1)); // 发送一条空消息对象
            }
        }
    }
}
